package com.huwaiwai001.mq.rocketmq;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;


public class RocketMqProducer {

    public static void main(String[] args) {
        DefaultMQProducer producer = new DefaultMQProducer("PID-test0426");
        producer.setNamesrvAddr("dev.config.duibar.com:9876");
        producer.setRetryTimesWhenSendAsyncFailed(0);
        try {
            producer.start();
            asyncProducer(producer);
        } catch (Exception e) {

        } finally {
            producer.shutdown();
        }
    }

    private static void syncProducer(DefaultMQProducer producer) throws Exception {
        Message message = new Message();
        byte[] body = ("who are u").getBytes(RemotingHelper.DEFAULT_CHARSET);
        message.setTopic("TopicPluginCenterOrderDev");
        message.setBody(body);
        SendResult result = producer.send(message);
        String msgId = result.getMsgId();
        System.out.println(msgId);
    }

    private static void asyncProducer(DefaultMQProducer producer) throws Exception {
        Message message = new Message();
        byte[] body = ("who are u").getBytes(RemotingHelper.DEFAULT_CHARSET);
        message.setTopic("TopicPluginCenterOrderDev");
        message.setBody(body);
        producer.send(message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("success " + sendResult.getMsgId());
            }
            @Override
            public void onException(Throwable throwable) {
                System.out.println("fail " + throwable.getMessage());
            }
        });
    }

    private static void onewayProducer(DefaultMQProducer producer) throws Exception {
        Message message = new Message();
        byte[] body = ("who are u").getBytes(RemotingHelper.DEFAULT_CHARSET);
        message.setTopic("TopicPluginCenterOrderDev");
        message.setBody(body);
        producer.sendOneway(message);
    }

}
